package com.asiainfo.iam.controller;


import com.asiainfo.iam.config.Result;
import com.asiainfo.iam.constant.DMConstant;
import com.asiainfo.iam.constant.VerificationConstant;
import com.asiainfo.iam.tool.ConnectThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;


/**
 * 整个达梦数据库签名/验签系统的入口点。
 * 该类主要负责解析命令行参数、建立数据库连接，并根据参数执行数据签名或验签操作。
 * <p>
 * 功能概述：
 * - 先连接数据库
 * - 如果缺少必要字段，添加加密字段
 * - 获取表的主键信息
 * - 执行签名操作（queryTableContentQianMing）或验签操作（queryTableContentYanQian）
 */
// TODO 7
//@ConditionalOnProperty(name = "enable.syn.controller", havingValue = "true")
@RequestMapping("/api/iam/sv")
@RestController
@Api(tags = "签名验签API")
public class VerificationStartController {
    private static final Logger log = LoggerFactory.getLogger(VerificationStartController.class);
//    @Value("dm.host")
//    public String host;
//    @Value("dm.port")
//    public String port;
//    @Value("dm.user")
//    public String user;
//    @Value("dm.password")
//    public String password;
//    @Value("dm.schema")
//    public String databaseName;

    @Autowired
    private DMDatabaseController dmDatabaseController;
    @Autowired
    private DMDatabaseOperateController dmDatabaseOperateController;
    @Autowired
    private ConnectThreadLocal connectThreadLocal;
    @Autowired
    SignatureVerificationController signatureVerificationController;

    //    @PostMapping("/connect")
//    public Result dmConnect(@RequestParam String host,
//                            @RequestParam String port,
//                            @RequestParam String user,
//                            @RequestParam String password){
//        try {
//            // 调用服务层创建连接
//            Connection connectionTest = dmDatabaseController.createConn(host, port, user, password);
//            connectThreadLocal.createConnection(host, port, user, password);
//            return Result.success("连接成功");
//        } catch (SQLException e) {
//            return Result.error("连接失败: " + e.getMessage());
//        }
//    }

//    @RequestParam String host,
//    @RequestParam String port,
//    @RequestParam String user,
//    @RequestParam String password,
//    @RequestParam String databaseName,
    @PostMapping("/signature")
    public Result toSignature(@Parameter(description = "表名称", required = true)
                              @RequestParam String tableName,
                              @Parameter(description = "需要签名的列表", required = true)
                              @RequestParam List<String> fields) {
        // 获得连接
//        try {
//            connectThreadLocal.createConnection(DMConstant.HOST,
//                    DMConstant.PORT,
//                    DMConstant.USER,
//                    DMConstant.PASSWORD);
//        } catch (SQLException e) {
//            throw new RuntimeException(e);
//        }
//        Connection connection = connectThreadLocal.getCurrentConnection();
        Connection connection = dmDatabaseController.createConn(DMConstant.HOST,
                DMConstant.PORT,
                DMConstant.USER,
                DMConstant.PASSWORD);
        log.info("---");
        //检查表中是否存在必须的签名字段

        try {
            // 检查表中是否存在必需的签名相关字段
            boolean hasB64SignedDataColumn = dmDatabaseOperateController.checkDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.B64SD, connection);
            boolean hasB64CertColumn = dmDatabaseOperateController.checkDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.B64CERT, connection);
            boolean hasVerifyColumn = dmDatabaseOperateController.checkDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.VERIFY, connection);
            boolean hasSignedDataUpdataTimeColumn = dmDatabaseOperateController.checkDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.SDUT, connection);
            boolean hasverifyyUpDataTimeColumn = dmDatabaseOperateController.checkDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.VUT, connection);


            // 如果缺少必要字段，则添加这些字段
            if (!hasB64SignedDataColumn) {
                dmDatabaseOperateController.addDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.B64SD, VerificationConstant.B64SD_TYPE, connection);
            }

            if (!hasB64CertColumn) {
                dmDatabaseOperateController.addDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.B64CERT, VerificationConstant.B64CERT_TYPE, connection);
            }

            if (!hasVerifyColumn) {

                dmDatabaseOperateController.addDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.VERIFY, VerificationConstant.VERIFY_TYPE, connection);
            }

            if (!hasSignedDataUpdataTimeColumn) {
                dmDatabaseOperateController.addDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.SDUT, VerificationConstant.SDUT_TYPE, connection);
            }

            if (!hasverifyyUpDataTimeColumn) {
                dmDatabaseOperateController.addDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.VUT, VerificationConstant.VUT_TYPE, connection);
            }

            // 获取表的主键字段
            List<String> findNameList = dmDatabaseOperateController.getPrimaryKeyOfDamengTable(DMConstant.SCHEMA, tableName, connection);

            //执行签名操作
            signatureVerificationController.signature(DMConstant.SCHEMA, tableName, connection, findNameList, fields);
            return Result.success("签名成功！");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @PostMapping("/verification")
    public Result toVerification(
            @Parameter(description = "表名称", required = true)
                                 @RequestParam String tableName,
                                 @Parameter(description = "需要验签的列表", required = true)
                                 @RequestParam List<String> fields) {

        // 获得连接
        Connection connection = dmDatabaseController.createConn(DMConstant.HOST,
                DMConstant.PORT,
                DMConstant.USER,
                DMConstant.PASSWORD);
        //检查表中是否存在必须的签名字段
        try {
            // 检查表中是否存在必需的签名相关字段
            boolean hasB64SignedDataColumn = dmDatabaseOperateController.checkDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.B64SD, connection);
            boolean hasB64CertColumn = dmDatabaseOperateController.checkDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.B64CERT, connection);
            boolean hasVerifyColumn = dmDatabaseOperateController.checkDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.VERIFY, connection);
            boolean hasverifyyUpDataTimeColumn = dmDatabaseOperateController.checkDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.VUT, connection);


            // 如果缺少必要字段，则添加这些字段
            if (!hasB64SignedDataColumn) {
                throw new RuntimeException("此表中没有 b64SignedData 列，无法执行验签动作");
            } else if (!hasB64CertColumn) {
                throw new RuntimeException("此表中没有 b64Cert 列，无法执行验签动作");
            } else {
                // 如果缺少可选字段，则添加这些字段
                if (!hasVerifyColumn) {
                    dmDatabaseOperateController.addDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.VERIFY, VerificationConstant.VERIFY_TYPE, connection);
                }
                if (!hasverifyyUpDataTimeColumn) {
                    dmDatabaseOperateController.addDataColumn(DMConstant.SCHEMA, tableName, VerificationConstant.VUT, VerificationConstant.VUT_TYPE, connection);
                }
            }
            // 获取表的主键字段
            List<String> findNameList = dmDatabaseOperateController.getPrimaryKeyOfDamengTable(DMConstant.SCHEMA, tableName, connection);

            //执行验签操作
            signatureVerificationController.verification(DMConstant.SCHEMA, tableName, connection, findNameList, fields);
            return Result.success("验签成功！");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
